const uniID = require('uni-id-common');
const db = uniCloud.database();
const SECRET_KEY = "mindSora@#";
const EXPIRES_IN = "2h";  // 令牌有效期

exports.main = async (event, context) => {
    const uniIDIns = uniID.createInstance({ context });
	
	let body = event;
	if (event.body != undefined) {
		body = JSON.parse(event.body)
	}

    try {
        // **身份验证**
		console.log(await uniIDIns.checkToken(body.uniIdToken))
        const { uid:userId } = await uniIDIns.checkToken(body.uniIdToken);
        if (!userId) {
            return { code: 403, msg: "身份验证失败" };
        }

		// 查询用户的预约时段
		const collection = db.collection("appoint_schedule");
		const result = await collection.where({ uid: userId }).get();

		if (!result.data || result.data.length === 0) {
			return { 
				success: false, 
				message: "未找到用户的预约记录" 
			};
		}

		const firstRecord = result.data[0];

		const consultantId = firstRecord.consultant;
		if (!consultantId) {
			return { 
				success: false, 
				message: "未找到咨询师信息" 
			};
		}

		// 生成咨询师 token
		const { token } = await uniIDIns.createToken({ uid: consultantId });

		return {
			token,
			success: true,
			data: {
				day: firstRecord.day,
				appointedSlots: firstRecord.appointedSlot
			}
		};
    } catch (error) {
        console.error("查询失败:", error);
        return {
            success: false,
            message: "查询失败",
            error: error.message
        };
    }
};
